package com.unibuy.smartdevice.ui.devs.vmc;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.unibuy.smartdevice.FragmentAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.controller.DevController;
import com.unibuy.smartdevice.databinding.RecyclerVmcBuyListBinding;
import com.unibuy.smartdevice.devices.PortTools;
import com.unibuy.smartdevice.exception.Logs;
import com.unibuy.smartdevice.exception.LogsEmptyException;
import com.unibuy.smartdevice.structure.BuyStructure;
import com.unibuy.smartdevice.structure.SlotStructure;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.ui.FontendActivity;
import com.unibuy.smartdevice.ui.dialog.DispatchDialog;
import com.unibuy.smartdevice.ui.tools.ImageGlide;
import com.unibuy.smartdevice.ui.dialog.BuyDialog;
import com.unibuy.smartdevice.utils.LanguageHelper;

import java.util.List;

public class RecyclerVmcBuyListAdpter extends RecyclerView.Adapter<RecyclerVmcBuyListAdpter.ViewHolder> {
    private Logs logs;
    private Context context;
    private final List<SlotStructure> SlotList;
    private FragmentAbstract fragment;

    public RecyclerVmcBuyListAdpter(FragmentAbstract fragment, List<SlotStructure> slotList) {
        this.logs = new Logs(this.getClass());
        this.context = fragment.getContext();
        this.SlotList = slotList;
        this.fragment = fragment;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        RecyclerVmcBuyListBinding binding;

        public ViewHolder(@NonNull RecyclerVmcBuyListBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 使用 ViewBinding 來綁定佈局
        RecyclerVmcBuyListBinding binding = RecyclerVmcBuyListBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);

        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        // 讀取最後設定語言的設定
        LanguageHelper.applySavedLanguage(context);
        SlotStructure slot = SlotList.get(position);
        String urlString = slot.getProduct().getProductImg();
        try {
            new ImageGlide(context).fileload(urlString, holder.binding.imageProductPicture);
        } catch (LogsEmptyException e) {
            this.logs.warning(e);
        }
        holder.binding.textSlot.setText(String.format("%03d", slot.getSlot()));
        //多國語的判斷
        String currentLang = LanguageHelper.getSavedLanguage(context);
        switch (currentLang) {
            case "tw":
                holder.binding.textProductName.setText(slot.getProduct().getProductName());
                break;
            case "en":
                holder.binding.textProductName.setText(slot.getProduct().getProductNameEn());
                break;
            case "ja":
                holder.binding.textProductName.setText(slot.getProduct().getProductNameJp());
                break;
        }


        int machinePrice = slot.getProduct().getMachinePrice();
        int sellingPrice = slot.getProduct().getSellingPrice();
        int memberPrice = slot.getProduct().getMemberPrice();
        int slotUpperLimit = slot.getProduct().getSlotUpperLimit();
        int count = slot.getCount();
        boolean isLock = slot.isLock();

        int price = machinePrice > 0? machinePrice: sellingPrice;

        holder.binding.textPrice.setText("NT$ "+price);

        holder.binding.mask.setVisibility(View.GONE);
        holder.binding.textMask.setText("");

        if (count <= 0) {
            holder.binding.mask.setVisibility(View.VISIBLE);
            holder.binding.textMask.setText("已經售完");//已經售完
        }

        if (isLock) {
            holder.binding.mask.setVisibility(View.VISIBLE);
            holder.binding.textMask.setText("暫停販售");
        }

        if (count > 0 && !isLock) {
            holder.binding.imageProductPicture.setOnClickListener(new imageProductPictureOnClickListener(position));
        } else {
            holder.binding.imageProductPicture.setOnClickListener(null);
        }

        devRunVMC(0);
    }

    @Override
    public int getItemCount() {
        return SlotList.size();
    }

    public void addSlotData(SlotStructure slotStructure) {
        SlotList.add(slotStructure);
        notifyItemInserted(SlotList.size() -1);
    }

    public class imageProductPictureOnClickListener implements View.OnClickListener {
        private int position;

        public imageProductPictureOnClickListener(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            SlotStructure slotProduct = SlotList.get(position);
            if (slotProduct.isLock()) return;
            if (MyApp.getInstance().isShowDialog) return;

//            SlotStructure slotProduct = SlotList.get(position);
            BuyStructure buyProduct = new BuyStructure(slotProduct.getField(), slotProduct.getSlot(), slotProduct.getProduct(), 1);
            MyApp.getInstance().getBuyList().add(buyProduct);
            fragment.getSrcHandlerMain().start(getClass().getSimpleName(), FontendActivity.Option.STOP_COUNTDOWN.getOption(), "stop countdown");
            new BuyDialog(context, fragment.getSrcHandlerMain()).show();

//            MyApp.getInstance().getDevXinYuanController().getReadBufferByNow(new DevDetectSlotByVMC(fragment.getSrcHandlerMain(), position), 2000L);
//            MyApp.getInstance().getDevXinYuanController().addSendBuffer(MyApp.getInstance().getDevXinYuanController().getDevXinYuan().checkSlot(slotProduct.getSlot()));
        }
    }

    public class DevDetectSlotByVMC extends DevController.ReadBufferOnScheduler {
        private int position;

        public DevDetectSlotByVMC(HandlerMain handlerMain, int position) {
            super(handlerMain);
            this.position = position;
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }

        @Override
        public void readBufferOnScheduler(DevController devController, HandlerMain handlerMain) {
            for (byte[] buffer: devController.getReadBufferByMax()) {
                if (buffer[0] == 0x02 && buffer[1] == 0x01 || buffer[0] == 0x02 && buffer[1] == 0x02 || buffer[0] == 0x02 && buffer[1] == 0x04) {
                    SlotStructure slotProduct = SlotList.get(position);
                    BuyStructure buyProduct = new BuyStructure(slotProduct.getField(), slotProduct.getSlot(), slotProduct.getProduct(), 1);
                    MyApp.getInstance().getBuyList().add(buyProduct);
                    handlerMain.start(getClass().getSimpleName(), FontendActivity.Option.STOP_COUNTDOWN.getOption(), "stop countdown");
                    new BuyDialog(context, fragment.getSrcHandlerMain()).show();

                    return;
                }
            }

            handlerMain.start(getClass().getSimpleName(), "@貨道尚未準備好，三秒後再點選");//@貨道尚未準備好，三秒後再點選
        }
    }

    private void devRunVMC(int slot){
        MyApp.getInstance().getDevXinYuanController().getReadBufferByNow(new DevSelectSlotByMICO(fragment.getHandlerMain(), slot, false, false));
    }

    private int testCount;
    private int checkCount;
    private boolean isCMD;
    private boolean inTheMiddle;
    private boolean isSuccess;
    private void initDev() {
        testCount = 0;
        checkCount = 0;
        isCMD = false;
        inTheMiddle = false;
        isSuccess = false;
    }

    public class DevSelectSlotByMICO extends DevController.ReadBufferOnScheduler {
        private int slot;
        private boolean isMico;
        private boolean isHeading;

        public DevSelectSlotByMICO(HandlerMain handlerMain, int slot, boolean isMico, boolean isHeading) {
            super(handlerMain);

            this.slot = slot;
            this.isMico = isMico;
            this.isHeading = isHeading;
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }

        @Override
        public void readBufferOnScheduler(DevController devController, HandlerMain handlerMain) {
            for (byte[] buffer: devController.getReadBufferByMax()) {
                getLogs().info("DevSelectSlotByMICO:" + PortTools.showHex(buffer));

                if (buffer[0] == 0x02) {
                    isCMD = true;

                    if (buffer[1] == 0x01 ||
                            buffer[1] == 0x02 ||
                            buffer[1] == 0x04) {
                        isSuccess = true;
                        break;
                    }
                }

                if (buffer[0] == 0x03 && buffer[1] == 0x03) {
                    isCMD = true;
                }
            }

            getLogs().info("vmc isCMD:" + isCMD + " isSuccess:" + isSuccess);

            if (isCMD) {
                if (isSuccess) {
                    initDev();
//                    getSrcHandlerMain().start(getClass().getSimpleName(), DispatchDialog.Option.SET_MESSAGE_TEXT.getOption(), "檢測貨道可出貨");
//                    if (isMico) {
//                        MyApp.getInstance().getDevXinYuanController().getReadBufferByNow(new DevMicoInfo65ByMICO(getHandlerMain(), slot, isHeading));
//                        MyApp.getInstance().getDevXinYuanController().addSendBuffer(MyApp.getInstance().getDevXinYuanController().getDevXinYuan().setMicoHeating(isHeading));
//                    } else {
//                        MyApp.getInstance().getDevXinYuanController().getReadBufferByNow(new DevGetProductByMICO(getHandlerMain(), slot));
//                        MyApp.getInstance().getDevXinYuanController().addSendBuffer(MyApp.getInstance().getDevXinYuanController().getDevXinYuan().getProduct(slot));
//                    }
                } else {
                    if (checkCount > 15) {
                        getSrcHandlerMain().start(getClass().getSimpleName(), DispatchDialog.Option.ERROR_PROCESS_GOODS.getOption(), "請檢查商品有無取出再確認取貨");
                    } else {
//                        getSrcHandlerMain().start(getClass().getSimpleName(), Option.SET_MESSAGE_TEXT.getOption(), "檢查中");
//                        MyApp.getInstance().getDevXinYuanController().getReadBuffer(new DevSelectSlotByMICO(getHandlerMain(), slot, isMico, isHeading));
                        checkCount++;
                    }
                }
            } else {
                if (testCount > 15) {
//                    getSrcHandlerMain().start(getClass().getSimpleName(), DispatchDialog.Option.ERROR_PROCESS_GOODS.getOption(), "下位機無回應 請等3秒後再重試");
                } else {
//                    MyApp.getInstance().getDevXinYuanController().getReadBufferByNow(new DevSelectSlotByMICO(getHandlerMain(), slot, isMico, isHeading));
//                    MyApp.getInstance().getDevXinYuanController().addSendBuffer(MyApp.getInstance().getDevXinYuanController().getDevXinYuan().selectSlot(slot));
                    testCount++;
                }
            }
        }
    }
}
